package bip.util.SendToQFKR;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;


public class SendToKR {
	/**
	 * 多层级的VO对象，且包含上传功能的样例
	 * 注意key的书写格式,类似EL表达式的方式，属性关系用'.', 列表和数组关系用[]，Map关系用["xxx"]
	 */

	//	public static void main(String[] args) throws Exception{
	//
	//		ObjectMapper objectMapper = new ObjectMapper();
	//
	//		// 构建FormValuesEntity实例
	//		FORMTransferEntity formValues = new FORMTransferEntity();
	//		// 设置各个属性值...
	//		// 例如：formValues.setFd_3d100d1c7801b4("编码值");
	//
	//		// 将实体转换为JSON字符串
	//		String jsonFormValues = objectMapper.writeValueAsString(formValues);
	//		String docSubject = "接口发起流程";
	//		String docCreator = "{\"PersonNo\":\"01625\"}";
	//
	//		AddNewsInRestTemplate(jsonFormValues,docSubject,docCreator,ComparisonEnum.FORM_Transfer.getFormId(),ComparisonEnum.FORM_Transfer.getProcessId());
	//	}

	public static String AddNewsInRestTemplate(String jsonFormValues, String docSubject, String docCreator, String fdModelId, String fdFlowId) throws IOException {
		OkHttpClient client = new OkHttpClient().newBuilder()
				.build();

		MediaType mediaType = MediaType.parse("text/plain");

		// 添加Authorization头信息
		String authCredentials = "bipuser:8LwKvoMridQL1p11";
		String encodedAuth = Base64.getUrlEncoder().encodeToString(authCredentials.getBytes(StandardCharsets.UTF_8));

		RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
				.addFormDataPart("docCreator", docCreator)
				.addFormDataPart("docStatus", "20")
				.addFormDataPart("docSubject", docSubject)
				.addFormDataPart("fdFlowId", fdFlowId)
				.addFormDataPart("fdModelId", fdModelId)
				.addFormDataPart("formValues", jsonFormValues)
				.build();

		Request request = new Request.Builder()
				.url("https://ekp.kryy.com.cn:8095/api/sys-modeling/appModelRestService/addModel")
				.header("Authorization", "Basic " + encodedAuth) // 添加Authorization头
				.method("POST", body)
				.build();

		Response response = client.newCall(request).execute();
		// 检查响应状态码
		if (!response.isSuccessful()) {
			throw new RuntimeException("Failed to add news: " + response.code() + " - " + response.message());
		}
		// 读取并处理响应体
		ResponseBody responseBody = response.body();
		if (responseBody != null) {
			String responseBodyString = responseBody.string();
			System.out.println("Response Body: " + responseBodyString);
			return responseBodyString;
		} else {
			System.out.println("Empty response body.");
			return "null";
		}
	}

}
